package com.example.demo.interceptors;

import com.alibaba.fastjson.JSON;
import com.example.demo.Exception.NotLoginException;
import com.example.demo.Result;
import com.example.demo.Utils.JwtUtil;
import com.example.demo.config.securityConfig;
import com.example.demo.security.UserDetailsService;
import io.netty.util.internal.StringUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;

@Component
public class JwtFilter extends OncePerRequestFilter {
    @Resource
    private JwtUtil jwtUtil;

    @Resource
    UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            String token = request.getHeader("Authorization");
            if (StringUtils.isEmpty(token) || !token.startsWith("Bearer ")) {
                handleError(response, "用户未登录!");
                return;
            }
            // 去掉"Bearer "前缀，并去除可能存在的首尾空格
            token = token.substring(7).trim();
            if (!jwtUtil.validateToken(token)) {
                handleError(response, "用户登录已经过期!");
            }
            String username = jwtUtil.getUsernameFromToken(token);
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


        filterChain.doFilter(request, response);
    }


    /**
     * 处理错误响应
     */
    private void handleError(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");

        Result<?> result = Result.error(401, message);
        response.getWriter().write(JSON.toJSONString(result));
    }


    /**
     * 设置不拦截的url
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String path = request.getRequestURI();
        return Arrays.stream(securityConfig.WHITE_LIST)
                .anyMatch(pattern ->
                        new AntPathMatcher().match(pattern, path)
                );
    }
}
